package com.wxx.interceptior;

import com.google.common.base.Splitter;
import com.wxx.common.Const;
import com.wxx.util.CookieUtil;
import com.wxx.util.JsonUtil;
import com.wxx.util.RedisPoolUtil;
import org.codehaus.jackson.type.TypeReference;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 权限限制
 */
public class PermissionsInterceptior implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String sessionId = CookieUtil.readLoginToken(request);
        //获取当前的权限地址 /bg/dicUser/toDicUserList;jsessionid=1F3EA8235E7FD7322DBDD01795F0926C
        String requestURI = request.getRequestURI();
        List<String> str = Splitter.on(";").splitToList(requestURI);
        String aclUrl = str.get(0);

        //从redis中获取该用户的权限列表
        String allURIByRoleId = RedisPoolUtil.get(sessionId+Const.CURRENT_URIBYROLEID);
        List<String> list = JsonUtil.string2Obj(allURIByRoleId, new TypeReference<List<String>>() {
        });

        if (list.contains(aclUrl)){
            System.err.println("通过,拦截路径" + aclUrl);
            return true;
        }else{
            System.err.println("没有权限");
            //跳转到无权限页面
            //如果request.getHeader("X-Requested-With") 返回的是"XMLHttpRequest"说明就是ajax请求，需要特殊处理 否则直接重定向就可以了
            if("XMLHttpRequest".equals(request.getHeader("X-Requested-With"))){
                //告诉ajax我是重定向
                response.setHeader("REDIRECT", "REDIRECT");
                //告诉ajax我重定向的路径
                response.setHeader("CONTENTPATH", "/jump/no_permission");
                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            }else{
                response.sendRedirect("/jump/no_permission");
            }
            return false;
        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
